//
//  IdCardUploadVC.swift
//  身份证+人脸 开始认证
//
//  Created by 千策万划-mini on 2025/5/2.
//

import Foundation

class IdCardUploadVC: BaseTableVC, UIImagePickerControllerDelegate & UINavigationControllerDelegate {

    var navTitle: String = ""
    var productCode: String = ""
    var isAuthFace: Bool = false // 开始认证人脸（已经认证了身份证）
    private var startTime: String = ""

    // MARK: - lazy
    lazy var navView: BaseNavView = {
        let result = BaseNavView()
        result.resetNavBackTitle(title: "Verify Identity", rightView: nil)
        result.leftTop = XY(0, 0)
        result.blockBack = { [weak self] in
            guard let self = self else { return }
            if isAuthFace == false {
                GB_Nav?.popViewController(animated: true)
            }else{
                self.viewDetainment.show()
            }
        }
        return result
    }()

    lazy var headerView: IdCardUploadContentView = {
        let result = IdCardUploadContentView()
        result.resetView(title: navTitle)
        result.blockClickUpload = { [weak self] in
            guard let self = self else { return }
            self.authNext()
        }
        return result
    }()

    lazy var btnNext: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(W(284), 58)
        result.setBackgroundImage(UIImage(named: "icon_bottom_btn_bg"), for: .normal)
        result.centerXBottom = XY(SCREEN_WIDTH / 2, SCREEN_HEIGHT - max(LEFT_MARGIN, getBottomSafeAreaHeight()))
        result.tag = 1
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)

        let label = OutlineLabel()
        label.resetView(
            title: "Next Step",
            textColor: COLOR_WHITE(),
            font: UIFont.customExtraBoldFont(size: 20),
            shadowColor: UIColor(hex: "#004600"),
            outlineColor: UIColor(hex: "#1B4506")
        )
        label.centerXCenterY = XY(result.width / 2, result.height / 2)
        result.addSubview(label)
        return result
    }()

    // 身份证示例
    lazy var viewIdCardExample: IdCardExampleView = {
        let result = IdCardExampleView()
        result.blockConfirmClick = { [weak self] in
            guard let self = self else { return }
            self.viewIdCardExample.hide()
            if self.isAuthFace == false {
                // 身份证 - 选择相机/相册
                self.startTime = GlobalMethod.getTimeStamp()
                self.viewChooseAlbumView.show()
            }else{
                // 人脸 - 跳转拍照
                GlobalMethod.isOpenCameraPermissions { isOpen in
                    DispatchQueue.main.async {
                        if isOpen { // 已开启相机
                            self.jumpFacePicture()
                        }
                    }
                }
            }
        }
        return result
    }()

    // 选择相机/相册
    lazy var viewChooseAlbumView: ChooseCameraAlbumView = {
        let result = ChooseCameraAlbumView()
        result.blockCameraClick = { [weak self] in
            guard let self = self else { return }
            GlobalMethod.isOpenCameraPermissions { isOpen in
                DispatchQueue.main.async {
                    if isOpen { // 已开启相机
                        self.viewChooseAlbumView.hide()
                        self.jumpCardTakePicture()
                    }
                }
            }
        }
        result.blockAlbumClick = { [weak self] in
            guard let self = self else { return }
//            GlobalMethod.isOpenAlbumPermissions { isOpen in
                DispatchQueue.main.async {
//                    if isOpen { // 已开启相册
                        self.openAlbum()
//                    }
                }
//            }
        }
        return result
    }()

    // 身份证信息确认
    lazy var viewInfoConfirm: IdCardConfirmInfoView = {
        let result = IdCardConfirmInfoView()
        result.blockBirthClick = { [weak self] in
            guard let self = self else { return }
            self.viewSelectBirth.scrollToDate(date: self.viewInfoConfirm.labelBirth.text)
            self.viewSelectBirth.show()
        }
        result.blockConfirmClick = { [weak self] in
            guard let self = self else { return }
            self.saveUserIdentityInfoOneItem()
        }
        return result
    }()

    // 选择出生日期
    lazy var viewSelectBirth: SelectBirthView = {
        let result = SelectBirthView()
        result.blockConfirmClick = { [weak self] in
            guard let self = self else { return }
            self.viewSelectBirth.hide()
            self.viewInfoConfirm.resetBirth(birth: self.viewSelectBirth.selectedDate)
        }
        return result
    }()

    // MARK: - viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
    }

    func configUI() {
        view.addSubview(navView)
        tableView.register(ChooseIdCardTypeCell.self, forCellReuseIdentifier: String(reflecting: ChooseIdCardTypeCell.self))
        tableView.height = SCREEN_HEIGHT - navView.bottom
        tableView.top = navView.bottom
        view.addSubview(btnNext)
        tableView.tableHeaderView = headerView
    }

    // MARK: -  相册
    // 打开相册
    func openAlbum() {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        present(imagePicker, animated: true, completion: nil)
    }

    // 选择图片完成
    func imagePickerController(_: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        if let selectedImage = info[.originalImage] as? UIImage {
            // 你可以在这里对选中的图片进行处理
            // 例如：self.imageView.image = selectedImage
            GlobalMethod.showLoadingView()
            HomeRequestApi.uploadImage(
                shed: "1",
                carry: productCode,
                wisest: "11",
                image: selectedImage,
                rag: navTitle
            ) { _, responseData in
                guard let res = responseData as? [String: Any] else { return }
                GlobalMethod.hideLoadingView()
                if let model = ModelUserIdentityInfoOther.deserialize(from: res) {
                    self.imageUploadSuccess(model: model)
                }
            } failure: { _, _ in
                GlobalMethod.hideLoadingView()
            }
        }
        dismiss(animated: true, completion: nil)
    }
    
    // 上传成功 - 显示确认信息
    func imageUploadSuccess(model: ModelUserIdentityInfoOther) {
        self.viewInfoConfirm.resetView(name: model.cautiously, number: model.half, birth: model.stubby)
        self.viewInfoConfirm.show()
        self.viewChooseAlbumView.hide()
    }

    // 取消选择
    func imagePickerControllerDidCancel(_: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }

    // MARK: - 点击事件
    @objc func btnClick(_ sender: UIControl) {
        feedback()
        sender.addClickAnimate()
        switch sender.tag {
        case 1:
            authNext()
        default:
            break
        }
    }

    // 认证下一步
    func authNext() {
        if isAuthFace == false {
            // 认证身份证
            viewIdCardExample.show()
        } else {
            // 认证人脸
            viewIdCardExample.resetFaceView()
            viewIdCardExample.show()
        }
    }
    
    // 跳转身份证拍照
    func jumpCardTakePicture() {
        let vc = TakePictureVC()
        vc.cardType = self.navTitle
        vc.productCode = self.productCode
        vc.blockUploadImageSuccess = { [weak self](model) in
            guard let self = self else { return }
            self.imageUploadSuccess(model: model)
        }
        GB_Nav?.pushViewController(vc, animated: true)
    }
    
    // 跳转人脸拍照
    func jumpFacePicture() {
        let startTime = GlobalMethod.getTimeStamp()
        let vc = FaceTakePictureVC()
        vc.cardType = self.navTitle
        vc.productCode = self.productCode
        vc.blockUploadFaceImageSuccess = { [weak self](model) in
            guard let self = self else { return }
            GlobalMethod.buryPoint(productCode: self.productCode, type: "4", startTime: startTime, endTime: GlobalMethod.getTimeStamp())
            self.requestProductDetail()
        }
        GB_Nav?.pushViewController(vc, animated: true)
    }
    
    // MARK: - request
    // 保存用户身份证信息（第一项）
    func saveUserIdentityInfoOneItem() {
        HomeRequestApi.saveUserIdentityInfoOneItem(
            birth: viewInfoConfirm.labelBirth.text,
            number: viewInfoConfirm.tfNumber.text ?? "",
            name: viewInfoConfirm.tfName.text ?? "",
            cardType: navTitle
        ){ request, responseData in
            self.viewInfoConfirm.hide()
            GlobalMethod.buryPoint(productCode: self.productCode, type: "3", startTime: self.startTime, endTime: GlobalMethod.getTimeStamp())
            // success - 开始人脸
            self.isAuthFace = true
            self.viewIdCardExample.resetFaceView()
            self.viewIdCardExample.show()
        } failure: { request, error in
                
        }
    }
    
    // 产品详情接口
    func requestProductDetail() {
        HomeRequestApi.productDetail(productCode: productCode) { request, responseData in
            guard let res = responseData as? [String: Any] else {return}
            if let model = ModelProductDetail.deserialize(from: res) {
                GlobalMethod.authNext(type: model.decides.died, productCode: self.productCode, orderCode: model.fiercely.hurriedly)
            }
        } failure: { request, error in
            
        }
    }
}
